package com.vt.common.core.util;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

public class WechatUnit {

    public static void main(String[] args) {
        Map params=new HashMap();
        params.put("appid","wxdcd1b0de02dc4c55");
        params.put("secret", "dfc99a4ebd6d34f7b48d65e288f210c1");

        params.put("template_id","4QE7_DZTEk5kcUbiYmIY3puv_gv--QMpDWMwCQFVqvU");
        params.put("touser", "oOg7X5SVBn4GQ3FsOl3XbRNg4C9M");
        params.put("url", "oOg7X5SVBn4GQ3FsOl3XbRNg4C9M");
        params.put("form_id", "oOg7X5SVBn4GQ3FsOl3XbRNg4C9M");
        String time1="2018-11-26";
        params.put("first", "您的订单已配送完成!");
        params.put("keyword1", "商家配送");
        params.put("keyword2", "联系商家");
        params.put("keyword3", time1);
        params.put("keyword4", time1);
        System.out.println(52);
        System.out.println(send_message(params));
        System.out.println(66);
    }



    /**
     * 微信发送通知
     *
     * @return
     * @throws
     */
    public static String  send_message(Map params) {
        String appid=params.get("appid").toString()==null?"":params.get("appid").toString();
        String secret=params.get("secret").toString()==null?"":params.get("secret").toString();
        String token=sendGet("https://api.weixin.qq.com/cgi-bin/token","grant_type=client_credential&appid="+appid+"&secret="+secret);
        JSONObject tokenMap=JSONUtil.parseObj(token);
        if(tokenMap!=null && tokenMap.get("access_token")!=null){
            Map parameters=new HashMap();
            String touser=params.get("touser").toString()==null?"":params.get("touser").toString();
            String template_id=params.get("template_id")==null?"":params.get("template_id").toString();
            String url=params.get("url")==null?"":params.get("url").toString();
            String form_id=params.get("form_id")==null?"":params.get("form_id").toString();
            parameters.put("touser", touser);
            Map weapp_template_msg=new HashMap();

            weapp_template_msg.put("template_id", template_id);
            weapp_template_msg.put("page", url);
            weapp_template_msg.put("form_id", form_id);

            weapp_template_msg.put("emphasis_keyword", "#FF0000");
            Map map=new HashMap();

            Iterator it = params.keySet().iterator();
            while(it.hasNext()){
                Map<String, String> smap=new HashMap();
                String key = it.next().toString();
                if(!key.equals("touser") && !key.equals("template_id")  && !key.equals("url") && !key.equals("appid")
                        && !key.equals("form_id") && !key.equals("secret")){
                    smap.put("value", params.get(key).toString().trim());
                    smap.put("color", "#173177");
                    map.put(key, smap);
                }
            }

            weapp_template_msg.put("data", map);
            parameters.put("weapp_template_msg",weapp_template_msg);
            String param=JSONUtil.toJsonStr(parameters);
            /* String ticket=sendPosts("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+tokenMap.get("access_token"),param);*/
            String ticket=sendPosts("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token="+tokenMap.get("access_token").toString(),param);
            JSONObject json = JSONUtil.parseObj(ticket);
            System.out.println(json.get("errmsg").toString());
            return json.get("errmsg").toString();
        }
        return "no";
    }

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 鎵撳紑鍜孶RL涔嬮棿鐨勮繛鎺?
            URLConnection connection = realUrl.openConnection();
            // 璁剧疆閫氱敤鐨勮姹傚睘鎬?
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 寤虹珛瀹為檯鐨勮繛鎺?
            connection.connect();
            // 瀹氫箟 BufferedReader杈撳叆娴佹潵璇诲彇URL鐨勫搷搴?
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("请求失败" + e);
            e.printStackTrace();
        }
        // 浣跨敤finally鍧楁潵鍏抽棴杈撳叆娴?
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }


    public static String sendPosts(String url,String parameters) {
        String result = "";// 返回的结果
        BufferedReader in = null;// 读取响应输入流
        PrintWriter out = null;
        StringBuffer sb = new StringBuffer();// 处理请求参数
        String params = "";// 编码之后的参数
        try {
            // 编码请求参数

            // 创建URL对象
            URL connURL = new URL(url);
            // 打开URL连接
            java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL
                    .openConnection();
            // 设置通用属性
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            // 设置POST方式
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            // 获取HttpURLConnection对象对应的输出流
            out = new PrintWriter(httpConn.getOutputStream());
            // 发送请求参数
            out.write(parameters);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应，设置编码方式
            in = new BufferedReader(new InputStreamReader(httpConn
                    .getInputStream(), "UTF-8"));
            String line;
            // 读取返回的内容
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


}
